package cn.bookingsmart.service;

import cn.bookingsmart.common.config.SystemConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by sun on 2017/9/12.
 *
 * @author sunfuchang03@126.com
 * @version 1.0
 * @since 1.0
 */
@Component
public class EsSyncTask {
    //~ Static fields/initializers =====================================================================================
    private static Logger log = LoggerFactory.getLogger(EsSyncTask.class);

    private static final String ES_SYNC_RETRY_TIMES_CONFIG = SystemConfig.get("es.sync.retry.times");
    public static int ES_SYNC_RETRY_TIMES = 5; // 默认重试5次

    //~ Instance fields ================================================================================================

    //~ Constructors ===================================================================================================


    //~ Methods ========================================================================================================

    public void start(int threadCount) {
        if (StringUtils.hasLength(ES_SYNC_RETRY_TIMES_CONFIG)) {
            ES_SYNC_RETRY_TIMES = Integer.valueOf(ES_SYNC_RETRY_TIMES_CONFIG);
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCount; i++) {
            executorService.execute(new SyncThread());
        }
    }

    /**
     * 同步线程
     */
    class SyncThread implements Runnable {
        @Override
        public void run() {
            while (true) {
                String tname = Thread.currentThread().getId() + "-" + Thread.currentThread().getName();
                System.out.println("[" + tname + "]任务开始...");
                long start = System.currentTimeMillis();
                try {
                    Thread.sleep(5 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                long end = System.currentTimeMillis();
                log.info("[" + tname + "]任务结束，耗时：" + (end - start) + "ms.");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}